package com.yjf.ljr.activity;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.yjf.ljr.R;
import com.yjf.ljr.application.MyApplication;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.LogOutDataClass;
import com.yjf.ljr.dataclass.LoginDataClass;
import com.yjf.ljr.dataclass.MyAccountDataClass;
import com.yjf.ljr.dataclass.MyAccountDataClass.MyAccountInfo;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AESUtil;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.Base64;
import com.yjf.ljr.util.SPreferences;

public class LoginActivity extends IjActivity implements OnClickListener {

	@ID("etLoginUsername")
	private EditText mEtLoginUsername;// username
	@ID("etLoginPassword")
	private EditText mEtLoginPassword;// password
	@ID("pwd_eyes")
	private CheckBox pwdEyes;

	@ID("btnLogin")
	private Button mBtnLogin;
	@ID("btn_title_left")
	private Button mBtTitleLeft;
	@ID("tv_title_right")
	private TextView mTvRegister;
	@ID("tvForgetPassword")
	private TextView mTvForgetPassword;
	private TextView mTvCancel;
	static LoginActivity instance;
	public static final String FIRST_LOGIN = "firstLogin";
	private final static int LOCKPATTERN_SETTING = 2;
	private MyApplication myApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_native);
		myApplication = (MyApplication) getApplication();
		setVerify(false);
		initControl();
	}

	private void initControl() {
		setLeftBtnClick();
		setRightStr("注册");
		setTitleStr("登录");
		instance = this;
		mBtnLogin.setOnClickListener(this);
		mTvRegister.setOnClickListener(this);
		mTvForgetPassword.setOnClickListener(this);
		mTvForgetPassword.setPaintFlags(mTvForgetPassword.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		AppUtil.setEditTextHintSize(mEtLoginUsername, "请输入您的用户名", 16);
		AppUtil.setEditTextHintSize(mEtLoginPassword, "登录密码", 16);
		String userName = SPreferences.getUserName(this);
		if (!TextUtils.isEmpty(userName)) {
			mEtLoginUsername.setText(userName);
		}
		pwdEyes.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					mEtLoginPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				} else {
					mEtLoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				}
			}
		});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String userName = SPreferences.getUserName(this);
		if (!TextUtils.isEmpty(userName)) {
			mEtLoginUsername.setText(userName);
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btnLogin:
			String userName = mEtLoginUsername.getText().toString().trim();
			if (TextUtils.isEmpty(userName)) {
				// showToast("请输入用户名！！！");
				showToast("请输入用户名！！！");
				return;
			}
			String pwd = mEtLoginPassword.getText().toString().trim();
			if (TextUtils.isEmpty(pwd)) {
				// showToast("请输入密码！！！");
				showToast("请输入密码！！！");
				return;
			}
			new LoginTask(userName, AESUtil.encode(pwd)).execute();
			showProgressDialog("正在登录");
			SPreferences.setUserName(this, userName);
			SPreferences.setPassword(this, pwd);
			break;
		case R.id.tv_title_right/* R.id.btnRegister */:
			mEtLoginPassword.setText("");
			startActivityForResult(new Intent(this, RegistrationActivity.class), CommonData.REQUEST_CODE_LOGIN);
			break;
		case R.id.tvForgetPassword:
			mEtLoginPassword.setText("");
			startActivity(new Intent(mContext, ForgetPasswordActivity.class));
			break;
		default:
			break;
		}
	}

	@Override
	@SuppressLint("NewApi")
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == LOCKPATTERN_SETTING) {
			setResult(RESULT_OK);
			LoginActivity.this.finish();
		} else if (requestCode == CommonData.REQUEST_CODE_LOGIN && resultCode == RESULT_OK) {
			String userName = SPreferences.getUserName(this);
			if (!TextUtils.isEmpty(userName)) {
				mEtLoginUsername.setText(userName);
			}
		}
	}

	class LoginTask extends AsyncTask<Void, Void, Void> {

		private String mFailStr;

		private String mUserName;
		private String mPassWord;
		private LoginDataClass dc = new LoginDataClass();

		public LoginTask(String username, String password) {
			super();
			this.mUserName = username;
			this.mPassWord = password;
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... param) {
			// TODO Auto-generated method stub
			RequestObject requestObject = new RequestObject();
			requestObject.method = "login";
			requestObject.map.put("userName", mUserName);
			String pwdStr = URLEncoder.encode(mPassWord);
			requestObject.map.put("passWord", pwdStr);

			String requrestUrl = RequestBuilder.build(requestObject);
			try {
				IjConnect.doRequest(requrestUrl, dc);
				if (dc.code == null) {
					mFailStr = getResources().getString(R.string.loaddata_exception);
				} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
					mFailStr = dc.msg;
				}
			} catch (Exception e) {
				// TODO: handle exception
				mFailStr = getResources().getString(R.string.loaddata_exception);
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			if (!TextUtils.isEmpty(mFailStr)) {
				dismissProgressDialog();
				showToast(mFailStr);
			} else {
				new AccountOverviewTask(mUserName).execute();
			}
		}

	}

	/** 获取账户信息 **/
	class AccountOverviewTask extends AsyncTask<Void, Void, String> {
		String username;

		public AccountOverviewTask(String username) {
			this.username = username;
		}

		private MyAccountDataClass dc = new MyAccountDataClass();

		@Override
		protected String doInBackground(Void... params) {
			RequestObject reqObj = new RequestObject();
			reqObj.method = "appMeAccount";
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			if ("-2".equals(dc.code)) {
				if (!TextUtils.isEmpty(result)) {
					showToast(result);
				} else {
					showToast("未对该角色开放app功能");
				}
				new LogOutTask().execute();
				CommonData.SESSIONID = "";
				CommonData.FLAG_LOGIN_SERVER = false;
				CommonData.IS_LOGIN = false;
				SPreferences.clearPassword(LoginActivity.this);
				MyAccountActivity.gIsLoginServer = false;
				return;
			}

			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				boolean isNeedSetting = false;
				CommonData.FLAG_LOGIN_SERVER = true;
				CommonData.IS_LOGIN = true;
				MyAccountActivity.gIsLoginServer = true;

				/***************** 手势密码 **************/

				String userName = username;
				if (dc.userInfos != null && dc.userInfos.size() > 1) {
					MyAccountInfo info = dc.userInfos.get(0);
					if (info != null) {
						userName = info.userName;
					}
				}
				CommonData.USER_NAME = userName;
				if (!TextUtils.isEmpty(userName)) {
					boolean isFirstLogin = (Boolean) SPreferences.getData(LoginActivity.this, true, userName
							+ FIRST_LOGIN);
					if (isFirstLogin) {
						isNeedSetting = true;
						SPreferences.saveData(LoginActivity.this, false, userName + FIRST_LOGIN);
						Intent intent = new Intent(LoginActivity.this, LockPatternActivity.class);
						intent.putExtra(FIRST_LOGIN, true);
						startActivityForResult(intent, LOCKPATTERN_SETTING);
					} else {
						boolean isOpen = (Boolean) SPreferences.getData(LoginActivity.this, false, CommonData.USER_NAME
								+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
						if (isOpen) {
							// 开启自动登陆
							myApplication.startAutoLogin();
						}
					}
				}
				if (!isNeedSetting) {
					setResult(RESULT_OK);
					LoginActivity.this.finish();
				}
			}
		}
	}

	/************* 退出登录 ***********/
	class LogOutTask extends AsyncTask<Void, Void, String> {
		LogOutDataClass dc = new LogOutDataClass();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected String doInBackground(Void... arg0) {
			RequestObject requestObject = new RequestObject();
			requestObject.method = "logout";
			return requestDataAndGetErrorMsg(requestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!(TextUtils.isEmpty(result))) {// faile
				// showToast(result);
				showToast(result);
			} else if ("1".equals(dc.result)) {// success
				// loginWebview();
			}
		}

	}
}
